package utility_jwt

import (
	"Sailor/app/Sailor-console-server/internal/model/entity"
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/golang-jwt/jwt/v5"
)

// ParseToken parses and validates the JWT token from the Authorization header.
func ParseToken(ctx context.Context, tokenString string) (*entity.SysUser, error) {
	if tokenString == "" {
		return nil, gerror.New("No token provided")
	}
	// Remove 'Bearer ' prefix if present
	if len(tokenString) > 7 && tokenString[:7] == "Bearer " {
		tokenString = tokenString[7:]
	}
	// Parse and validate the token
	claims := &JWTClaims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return g.Cfg().MustGet(ctx, "jwt.secret").Bytes(), nil
	})

	if err != nil || !token.Valid {
		return nil, gerror.New("Invalid token")
	}
	return &claims.UserInfo, nil
}
